package cfca.paperless.client.servlet._3_assist._3_03_TransformPdfToImage;

import java.io.File;

import org.apache.commons.io.FileUtils;

import cfca.paperless.client.servlet.PaperlessClient;
import cfca.paperless.client.servlet.PaperlessConfig;
import cfca.paperless.client.util.Base64;
import cfca.paperless.client.util.GUID;
import cfca.paperless.client.util.IoUtil;
import cfca.paperless.client.util.StringUtil;

/**
 * @Description PDF自动化转图片接口，使用示例。
 * 
 * @Author dell
 * @Date 2016-5-16
 * @CodeReviewer TODO
 */
public class TransformPdfToImageTest01 {

    public static void main(String[] args) throws Exception {

        long timeStart = System.currentTimeMillis();// 开始时间

        System.out.println("TransformPdfToImageTest01 START");

        PaperlessClient clientBean = new PaperlessClient(PaperlessConfig.assistUrl, 10000, 60000);// 无纸化辅助接口的访问URL

        String pdfFilePath = "./TestData/file.pdf";// pdf文件

        String pdfSuffix = IoUtil.getFileNameSuffix(pdfFilePath);
        if (!PaperlessConfig.PDF_FILE_SUFFIX.equals(pdfSuffix)) {
            throw new Exception("所选文件不是pdf文件");
        }

        byte[] pdfFile = FileUtils.readFileToByteArray(new File(pdfFilePath));

        String pageNo = "-1";// 需要转图片的页码，值为-1或者0时代表全部

        String systemNo = GUID.generateId();// 业务流水号 

        String result = clientBean.transformPdfToImage(systemNo, pdfFile, pageNo, PaperlessConfig.operatorCode, PaperlessConfig.channelCode);

        String code = StringUtil.getNodeText(result, "Code");

        // 处理结果为正常，保存生成的图片文件到本地目录下
        if ("200".equals(code)) {
            System.out.println("TransformPdfToImageTest01 END OK");
            
            String imageBase64 = StringUtil.getNodeText(result, "Image");// 图片的base64编码
            System.out.println(imageBase64.length());
            
            if (pageNo.equals("-1") || pageNo.equals("0")) {
                String[] imageData = imageBase64.split(":");
                System.out.println("imageData size:" + imageData.length);
                
                for (int i = 0; i < imageData.length; i++) {
                    IoUtil.write("./TestData/output/TransformPdfToImageTest01-" + (i + 1) + ".png", Base64.decode(imageData[i]));
                }
            } else {
                IoUtil.write("./TestData/output/TransformPdfToImageTest01.png", Base64.decode(imageBase64));
            }
            System.out.println("OK");
        } else {
            // 处理结果为异常，打印出错误码和错误信息
            System.out.println("TransformPdfToImageTest01 END NG");
            System.out.println(result);
        }

        long timeEnd = System.currentTimeMillis();// 结束时间
        System.out.println("##########" + "time used:" + (timeEnd - timeStart) + "##########");

    }

}
